package com.example.picturebacked.api.imagesearch.sub;

import com.example.picturebacked.exception.BusinessException;
import com.example.picturebacked.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Autheor LBT
 * 使用Jsoup进行爬取HTML页面，提取页面中包含firstUrl的JavaScript脚本，并返回图片列表的页面地址
 */
@Slf4j
public class GetImageFirstUrlApi {
    /**
     * 使用Jsoup获取图片页面地址
     */
    public static String getImageFirstUrl(String url) {
        try {
            Document document = Jsoup.connect(url)
                    .timeout(5000)
                    .get();
            // 获取所有Script标签
            Elements scriptElements = document.getElementsByTag("script");
            for (Element script : scriptElements) {
                String scriptContent = script.html();
                if (scriptContent.contains("\"firstUrl\"")) {
                    // 在正则表达式提取firstUrl的值
                    Pattern pattern = Pattern.compile("\"firstUrl\"\\s*:\\s*\"(.*?)\"");
                    // 使用Matcher类进行匹配
                    Matcher matcher = pattern.matcher(scriptContent);
                    if (matcher.find()) {
                        // 找到firstUrl的值
                        String firstUrl = matcher.group(1);
                        // 处理转义字符
                        firstUrl = firstUrl.replace("\\/", "/");
                        return firstUrl;
                    }
                }
            }
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未找到url");
        } catch (IOException e) {
            log.error("搜索失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "搜索失败");
        }
    }

    public static void main(String[] args) {
        String url = "https://graph.baidu.com/s?card_key=&entrance=GENERAL&extUiData[isLogoShow]=1&f=all&isLogoShow=1&session_id=11082342167474394930&sign=1216589b27c2cc9ca48d901756901527&tpl_from=pc";
        String imageFirstUrl = getImageFirstUrl(url);
        System.out.println("搜索成功，结果URL：" + imageFirstUrl);
    }
}




















